package com.dfbz.dao;


import com.dfbz.constant.Const;
import com.dfbz.dao.base.BaseDao;
import com.dfbz.model.Conference;
import com.dfbz.utils.JDBCUtil;
import com.dfbz.utils.StrUtil;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class MeetDao extends BaseDao<Conference> {


    /**
     * 分页查询会议信息
     *
     * @return 会议列表
     */
    public List<Conference> findList(int page, int deptId, String search) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        //开启下划线->驼峰转换所用
        RowProcessor processor = new BasicRowProcessor(new GenerousBeanProcessor());
        List<Conference> list = null;
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("select * from conference where id <> 0 and ");
            if (StrUtil.isNotEmpty(search)) {
                sql.append("title like '%").append(search).append("%' and ");
            }
            if (0 != deptId) {
                sql.append("dept_id = ").append(deptId).append(" and ");
            }
            sql.delete(sql.lastIndexOf("and"), sql.length());
            int start = (page - 1) * Const.MAX_PAGE_SIZE;
            int end = Const.MAX_PAGE_SIZE;
            sql.append("order by id desc limit ").append(start).append(",").append(end);
            list = qr.query(sql.toString(), new BeanListHandler<>(Conference.class, processor));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;

    }

    /**
     * 查看会议内容的总数量
     * @param deptId 部门ID
     * @param search 搜索内容
     * @return 总数量
     */
    public long getTotalMeet(int deptId, String search) {
        long total = 0L;
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("select count(*) as total from conference where id <> 0 and ");
            if (StrUtil.isNotEmpty(search)) {
                sql.append("title like '%").append(search).append("%' and ");
            }
            if (0 != deptId) {
                sql.append("dept_id = ").append(deptId).append(" and ");
            }
            sql.delete(sql.lastIndexOf("and"), sql.length());
            Map<String, Object> map = qr.query(sql.toString(), new MapHandler());
            total = Long.parseLong(map.get("total").toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return total;
    }
}
